<!-- 月产量统计 -->
<template>
  <div class="app-container">
    <Find :OriginalFilter="{ static: true }" :formList="formList" @findClicked="findClicked" />
    <div class="flex mt10" style="width: 100%; background-color: white">
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
        <JTable
          :objectSpanObj="objectSpanMethod(tableData)"
          :tableHeader="tableHeader"
          :tableData="tableData"
          class="mt10"
          :isLoading="isLoading"
          @currentRow="currentRow"
          :headerStyle="headerStyle"
        />
      </el-card>
    </div>
    <el-card shadow="never" :body-style="{ padding: '5px' }">
      <PageModule :pageSize="pageSize" :PageData="{ total, buttonS: true }" @pageSizeChange="handleSizeChange" @pageChange="handleCurrentChange" />
    </el-card>

    <el-drawer v-model="drawer" :direction="'ttb'" size="small" :with-header="false">
      <span @click="drawer = false" style="float: right; cursor: pointer; color: rgb(7, 7, 7)">X</span>
      <div class="flex AIC" style="flex-direction: column">
        <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }" style="width: 100%">
          <h1 class="f24 flex JCC">{{ currentTableRow.qty1 }} {{ currentTableColumn.label }} 生产明细</h1>
          <Table
            :summaryData="summaryData10"
            summary
            :tableHeader="tableHeader10"
            :tableData="tableData10"
            class="mt10"
            :outTableHeight="150"
            @currentRow="currentRow10"
          />
        </el-card>
      </div>
    </el-drawer>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import LoginWork from '@/utils/LoginWork'
import { selectList } from '@/plugins/mixin'
import { debounce } from 'lodash'
import service from '@/utils/request'
import fileRequest from '@/utils/fileRequest'
import JMessage from '@/utils/JMessage'
export default defineComponent({
  name: 'DayOutput'
})
</script>

<script lang="ts" setup>
import { i18n, Jzhcn } from '@/i18n'
import { onMounted, ref, watch } from 'vue'
const headerStyle = { 'background-color': '#CCFFFF', color: 'red', fontSize: '15px', padding: '0', height: '30px' }

const getCurrentTime = () => {
  const date = new Date()
  const year = String(date.getFullYear())
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const dayOfMonth = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${dayOfMonth}`
}
// 获取当月最后一天
const getLastDayOfMonth = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const lastDay = new Date(year, month, 0)
  return lastDay.toISOString().split('T')[0]
}
const formList = ref([
  {
    type: 'dateSingle',
    dateLabel: '生产日期',
    dateValue: getCurrentTime()
  },
  {
    type: 'dateSingle',
    dateLabel: '至',
    dateValue: getLastDayOfMonth()
  },
  {
    type: 'button',
    checkboxLabel: '置空'
  },
  {
    type: 'button',
    checkboxLabel: '导出'
  }
])
// 表一模块
const tableHeader = ref([
  {
    prop: 'qty1',
    label: '单位'
  },
  {
    backgroundColor: true,
    prop: 'qty2',
    label: '部门'
  },
  {
    backgroundColor: true,
    prop: 'qty3',
    label: '年度合计'
  }
])
// 表一按钮
const findClicked = async (content: string) => {
  if (content === '置空') {
    formList.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
  if (content === '导出') {
    const res = (await fileRequest.get(`/GenerateProdReport/exportMonthProd?year=${formList.value[0].dateValue}`)) as any
    const link = document.createElement('a') // 利用a标签自定义下载文件名
    let blob = new Blob([res.data]) // 创建Blob对象，设置文件类型
    link.style.display = 'none'
    //设置连接
    link.href = window.URL.createObjectURL(blob)
    const FileName = decodeURI(res.headers['content-disposition'].split(`filename=`)[1])
    link.download = FileName //自定义文件名字
    document.body.appendChild(link)
    //模拟点击事件a
    link.click()
    document.body.removeChild(link)
  }
}
const tableData = ref([]) as any
const isLoading = ref(true)
// 分页器
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getTableList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getTableList()
}
// 获取表数据
const getTableList = debounce(async () => {
  isLoading.value = true
  let tableDataList = await service.post<any, any>(
    `/GenerateProdReport/getDaily/report?startDate=${formList.value[0].dateValue}&endDate=${formList.value[1].dateValue}`,
    {
      pageSize: pageSize.value,
      pageNum: currentPage.value
    }
  )
  isLoading.value = false
  tableHeader.value.splice(3, tableHeader.value.length)
  tableDataList.otherList.forEach((item: any, index: any) => {
    tableHeader.value.push({
      backgroundColor: true,
      prop: 'qty' + (index + 4),
      label: item
    })
  })
  tableDataList.list.map((item: any) => {
    const obj = {} as any
    item.map((item: any, index: any) => {
      obj[`qty${index + 1}`] = item
    })
    tableData.value = [...tableData.value, obj]
  })
  total.value = tableDataList.total
  const res = objectSpanMethod(tableData.value)
}, 500)
// 合并规则
const objectSpanMethod = (tableData: any) => {
  let spanArr: any[] = []
  let pos = 0
  let prodStepMap = new Map()

  // 遍历数据，找出相同单位的行
  tableData.forEach((item: any, index: any) => {
    if (index === 0) {
      spanArr.push(1)
      pos = 0
      prodStepMap.set(item.qty1, [index])
    } else {
      // 如果当前行的单位和上一行相同
      if (item.qty1 === tableData[index - 1].qty1) {
        spanArr[pos] += 1
        spanArr.push(0)
        prodStepMap.get(item.qty1).push(index)
      } else {
        spanArr.push(1)
        pos = index
        prodStepMap.set(item.qty1, [index])
      }
    }
  })
  return ({ row, column, rowIndex, columnIndex }: any) => {
    if (columnIndex === 0) {
      // 只合并第一列（单位列）
      const rowspan = spanArr[rowIndex]
      const colspan = rowspan > 0 ? 1 : 0
      return {
        rowspan,
        colspan
      }
    }
  }
}
onMounted(() => {
  getTableList()
})
watch(
  () =>
    formList.value.map((item: any) => {
      item.selectValue, item.inputValue, item.dateValue, item.checked
    }),
  () => {
    getTableList()
  }
)
// 点击表给另一张表传数据
const currentTableRow = ref({}) as any
const currentTableColumn = ref({}) as any
const currentRow = async (row: any = tableData.value[0], column: any = tableHeader.value[0]) => {
  currentTableRow.value = row
  currentTableColumn.value = column
  drawer.value = true
  getTableList10(row, column)
}
const imgList10 = ref([])
const drawer = ref(false)
const tableHeader10 = ref([
  {
    label: '品牌',
    prop: 'brand'
  },
  {
    label: '型体',
    prop: 'style'
  },
  {
    label: '颜色',
    prop: 'color'
  },
  {
    type: 'img',
    label: '图片',
    fixed: true,
    prop: 'photoPath',
    srcList: imgList10
  },
  {
    label: '指令号',
    prop: 'lotNo'
  },
  {
    label: '订单数',
    prop: 'orderQty'
  },
  {
    label: '生产数',
    prop: 'prodQty'
  }
])
const tableData10 = ref([])
interface summaryDataType {
  index: number
  num: number | undefined
}
const summaryData10 = ref<summaryDataType[]>([
  {
    index: 6,
    num: 0
  }
])
const getTableList10 = async (row: any, column: any) => {
  const res = await service.post<any, any>(
    `/GenerateProdReport/getDaily/report/detail?prodStep=${row.qty1}&deptName=${row.qty2}&date=${column.label}`
  )
  tableData10.value = res.dtoList
  summaryData10.value[0].num = res.prodQtySum
  imgList10.value = res.dtoList.map((item: any) => item.photoPath)
}
const currentTable10Row = ref({}) as any
const currentRow10 = async (row: any = tableData10.value[0]) => {
  currentTable10Row.value = row
}
</script>
<style lang="less" scoped>
.el-table__header {
  :deep(.cell) {
    background-color: '#CCFFFF' !important;
  }
}

table {
  table-layout: auto !important;
}

:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
}
</style>
